import { json, useRoutes } from "react-router-dom";
import { MenuFoldOutlined, MenuUnfoldOutlined, UserOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { Layout, Menu, Avatar, Dropdown, Space, Button, theme, notification } from 'antd';
import React, { useState, useEffect } from 'react';
const { Header, Sider, Content } = Layout;
import { getMenus, useProxyLogin } from './menu';
import { useNavigate } from "react-router-dom";
import './home.scss'
import radomCallback from "../../utils/radomCallback";


export default function Home() {

  const [api, contextHolder] = notification.useNotification();



  useEffect(() => {

    const ter = radomCallback(() => {
      console.log("还在触发你");
      api.info({
        message: `通知`,
        description: <div>您有新消息，请注意查收</div>,
      });
    });

    return () => {
      clearInterval(ter)
    }
  }, []);


  const [navs, setNavs] = useState([]);

  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate()
  const linkPage = ({ key }) => {
    navigate(key)
  }

  useProxyLogin((data) => {
    if (navs.some((item) => item.pathname === data.pathname) || data.pathname == '/home') {
      return;
    }
    setNavs([
      ...navs,
      {
        pathname: data.pathname,
        label: getMenuName(data.pathname),
      },
    ]);
  });

  /**
 * 通过路由的path，拿到菜单的名字
 */
  const getMenuName = (path) => {
    let label = "";

    const getName = (menus = getCurrentMenus()) => {
      menus.forEach((item) => {
        if (item.path === path) {
          label = item.label;
          return label;
        }

        if (item.children) {
          getName(item.children);
        }
      });
    };
    getName();

    return label;
  };

  const delNav = (event, index) => {
    // 阻止冒泡
    event.stopPropagation();

    /**
     * 拿到当前删除的那一项
     */
    const [delItem] = navs.splice(index, 1);

    // 当前删除的那一项，是高亮的
    if (delItem.pathname === location.pathname) {
      navigate(navs[navs.length - 1].pathname);
    }

    // 渲染
    setNavs([...navs]);
  };


  /**
 * 根据当前角色获取当前有权限的菜单
 */
  const getCurrentMenus = (menus = getMenus()) => {
    let currentRoles = [];
    if (localStorage.getItem("roles")) {
      currentRoles = JSON.parse(localStorage.getItem("roles"));
    }

    return menus.filter((item) => {
      if (item.children) {
        item.children = getCurrentMenus(item.children);
      }
      return item.roles.some((role) => currentRoles.includes(role));
    });
  };



  const routerComps = useRoutes(getCurrentMenus());

  const items = [
    {
      label: '退出登录',
      key: '0',
    },

  ];
  const logout = ({ key }) => {
    if (key === "0") {
      localStorage.clear();
      navigate("/login");
    }
  };
  return (
    <Layout className='layout'>
      {contextHolder}
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="logo " > 管理 </div>
        <Menu
          onClick={linkPage}
          theme="dark"
          mode="inline"
          items={getMenus()}
        />
      </Sider>
      <Layout>
        <Header
          className="site-layout-background"
          style={{ padding: 0, }} >

          {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
            className: 'trigger',
            onClick: () => setCollapsed(!collapsed),
          })}
          <Space>
            {navs.map((item, index) => (
              <Button
                onClick={() => navigate(item.pathname)}
                type={location.hash.includes(item.pathname) ? "primary" : "default"}
                key={index}
              >
                {item.label}
                {navs.length !== 1 && (
                  <CloseCircleOutlined
                    onClick={(event) => delNav(event, index)}
                  />
                )}
              </Button>
            ))}
          </Space>
          <Dropdown
            menu={{
              items,
              onClick: logout
            }}
            trigger={['click']}
          >

            <a onClick={(e) => e.preventDefault()}>
              <Space>
                <Avatar className='avatar' icon={<UserOutlined />} />
              </Space>
            </a>
          </Dropdown>
        </Header>
        <Content className="site-layout-content" >
          {routerComps}
        </Content>
      </Layout>


    </Layout>

  )
}